package com.woniuxy.commons.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.commons.utile.Result;
import com.woniuxy.controller.dto.AccountDto;
import com.woniuxy.dao.model.LoginLogs;
import com.woniuxy.service.LoginLogsService;
import com.woniuxy.service.MenuInfoService;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.InternetAddress;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.logging.SimpleFormatter;

@Service
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private MenuInfoService menuInfoService;

    @Resource
    private LoginLogsService loginLogsService;

    private ObjectMapper om = new ObjectMapper();
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

        //设置字符编码以及响应上下文类型
        response.setContentType("application/json;charset=utf8");
        response.setCharacterEncoding("utf8");

        AccountDto accountDto = new AccountDto();

        AccountDto accountDto1 =(AccountDto)authentication.getPrincipal();

        accountDto.setAccount(accountDto1.getAccount());
        accountDto.setId(accountDto1.getId());
        accountDto.setAccountPhone(accountDto1.getAccountPhone());
        accountDto.setAccountName(accountDto1.getAccountName());
        accountDto.setAccountEmail(accountDto1.getAccountEmail());
        accountDto.setAccountTouXin(accountDto1.getAccountTouXin());
        accountDto.setState(accountDto1.getState());

        //登录日志
        LoginLogs loginLogs = new LoginLogs();
        //获取登录的IP地址
        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        loginLogs.setIp(hostAddress);
//        //获取登录时间    改用自动填充
//        Date date = new Date();
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String format = simpleDateFormat.format(date);
//        loginLogs.setLogontime(format);
        loginLogs.setAccount(accountDto1.getAccount());
        //保存登录日志
        boolean save = loginLogsService.save(loginLogs);

        Result result = new Result().setMessage("登录成功").setData(accountDto).setCode(200);

        String json = om.writeValueAsString(result);

        response.getWriter().write(json);
        response.getWriter().flush();
    }
}
